package com.qsmx.store.app.main.mem;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.beloo.widget.chipslayoutmanager.gravity.IChildGravityResolver;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.event.CardReadEvent;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.fustion.FustionTag;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.goods.entity.GoodsEntity;
import com.qsmx.store.app.main.mem.adapter.MemCardSaleSuitAdapter;
import com.qsmx.store.app.main.mem.entity.MemCardOrderCreatEntity;
import com.qsmx.store.app.main.mem.entity.MemCardSaleEntity;
import com.qsmx.store.app.util.CardReadUtil;
import com.qsmx.store.app.util.CountDownTimerUtil;
import com.qsmx.store.app.util.DisplayUtil;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.app.widget.MyDialog;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.event.QrScanEvent;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.fusion.FusionString;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;
import com.qsmx.store.core.util.dimen.DimenUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;

public class MemCardSaleSuitDelegate extends AtmosDelegate {

    MemCardSaleSuitAdapter mAdapter;
    private List<MemCardSaleEntity> mCardData;
    private char mCardIcTag = 0x04;
    private char mCardNoTag = 0x3c;
    private boolean isReadNow = false;
    private Dialog saleSuitDialog;
    private AppCompatTextView tvCardNum;
    private String readCardNum;
    private MemCardSaleEntity mData;
    private AppCompatEditText etMemName;
    private AppCompatEditText etMemPersonNo;
    private AppCompatEditText etMemPhone;
    private MyDialog mPayStatusDialog = null;
    private String mPayMethod;
    private CountDownTimerUtil timer;
    private String mCurrentBillNo;

    @BindView(R2.id.rlv_mem_card_suit)
    RecyclerView rlvMemCardSuit;

    @Override
    public Object setLayout() {
        return R.layout.delegate_mem_card_sale_suit;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        initRecycler();
        initData();

    }

    private void initData() {

        HttpHelper.RestClientGet(new WeakHashMap<String, Object>(), HttpUrl.MEM_CARD_SALL,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<List<MemCardSaleEntity>>() {
                        }.getType();
                        Gson gson = new Gson();
                        mCardData = gson.fromJson(response, type);

                        mAdapter.setData(mCardData);
                        mAdapter.notifyDataSetChanged();
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void initRecycler() {

        ChipsLayoutManager manager = ChipsLayoutManager
                .newBuilder(getContext())
                //set vertical gravity for all items in a row. Default = Gravity.CENTER_VERTICAL
                .setChildGravity(Gravity.TOP)
                //whether RecyclerView can scroll. TRUE by default
                .setScrollingEnabled(true)
                //set maximum views count in a particular row
                .setMaxViewsInRow(6)
                //set gravity resolver where you can determine gravity for item in position.
                //This method have priority over previous one
                .setGravityResolver(new IChildGravityResolver() {
                    @Override
                    public int getItemGravity(int position) {
                        return Gravity.CENTER;
                    }
                })
                //a layoutOrientation of layout manager, could be VERTICAL OR HORIZONTAL. HORIZONTAL by default
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                // row strategy for views in completed row, could be STRATEGY_DEFAULT, STRATEGY_FILL_VIEW,
                //STRATEGY_FILL_SPACE or STRATEGY_CENTER
                .setRowStrategy(ChipsLayoutManager.STRATEGY_DEFAULT)
                // whether strategy is applied to last row. FALSE by default
                .withLastRow(true)
                .build();

        mAdapter = new MemCardSaleSuitAdapter(getContext());
        rlvMemCardSuit.setAdapter(mAdapter);
        rlvMemCardSuit.setLayoutManager(manager);

        mAdapter.setonItemClickListener(new MemCardSaleSuitAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mData = mCardData.get(position);
                showMemCardSaleDialog();
                DisplayUtil.showPayCardDisplay(getContext());
            }
        });

    }

    @SuppressLint("SetTextI18n")
    private void showMemCardSaleDialog() {
        saleSuitDialog = new Dialog(getContext(), R.style.dialog);
        saleSuitDialog.setCancelable(true);
        saleSuitDialog.show();
        Window window = saleSuitDialog.getWindow();
        window.setContentView(R.layout.dialog_mem_card_suit);
        int width = (int) (DimenUtil.getScreenWidth() * 0.6);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatImageView ivClose = window.findViewById(R.id.iv_close);
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saleSuitDialog.dismiss();
            }
        });
        AppCompatImageView ivCardScan = window.findViewById(R.id.iv_card_scan);
        tvCardNum = window.findViewById(R.id.tv_ic_card_num);
        AppCompatTextView tvMemCardGroup = window.findViewById(R.id.tv_mem_card_mem_group);
        AppCompatTextView tvMemIntoMoney = window.findViewById(R.id.tv_mem_into_money);
        AppCompatTextView tvMemCardMoney = window.findViewById(R.id.tv_mem_card_mem_money);
        AppCompatTextView tvMemSendCoin = window.findViewById(R.id.tv_mem_send_coin);
        AppCompatTextView tvMemCardDate = window.findViewById(R.id.tv_mem_card_mem_date);
        AppCompatTextView tvReceiveMoney = window.findViewById(R.id.tv_receive_money);

        etMemName = window.findViewById(R.id.et_mem_name);
        etMemPersonNo = window.findViewById(R.id.et_mem_person_card);
        etMemPhone = window.findViewById(R.id.et_mem_phone_num);

        tvMemCardGroup.setText(getString(R.string.mem_card_mem_group) + mData.getMemberGrade().getGradeName());
        tvMemIntoMoney.setText(getString(R.string.mem_card_mem_into_money) + mData.getMemberGrade().getGradeAdmissionFee() + "元");
        tvMemCardMoney.setText(getString(R.string.mem_money) + mData.getMemberGrade().getDeposit() + "元");
        tvMemSendCoin.setText(getString(R.string.mem_card_mem_send_coin) + mData.getCoins() + "币");
        tvMemCardDate.setText(getString(R.string.mem_card_expiration_date) + mData.getMemberGrade().getGradeValidDays() + "天");
        tvReceiveMoney.setText("￥" + mData.getPrice());
        ivCardScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isReadNow) {
                    CardReadUtil.StartGetCardNum(getContext(), mCardNoTag, new CardReadEvent(new Bundle()));
                    isReadNow = true;
                }
            }
        });

        AppCompatTextView tvCashPay = window.findViewById(R.id.tv_cash_pay);
        AppCompatTextView tvQrPay = window.findViewById(R.id.tv_qr_pay);
        tvCashPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayMethod = "1";
                if (StringUtil.isNotEmpty(etMemName.getText().toString()) && StringUtil.isNotEmpty(etMemPhone.getText().toString())) {

                    if (!isReadNow) {
                        CardReadUtil.StartGetCardNum(getContext(), mCardIcTag, new CardReadEvent(new Bundle()));
                        isReadNow = true;
                    }
                }
            }
        });

        tvQrPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayMethod = "2";
                if (StringUtil.isNotEmpty(etMemName.getText().toString()) && StringUtil.isNotEmpty(etMemPhone.getText().toString())) {
                    if (!isReadNow) {
                        CardReadUtil.StartGetCardNum(getContext(), mCardIcTag, new CardReadEvent(new Bundle()));
                        isReadNow = true;
                    }
                }
            }
        });

    }

    private void createOrder(String icNo, final String payMethod) {
        JSONObject params = new JSONObject();
        params.put("deptId", String.valueOf(FustionManager.mMachineData.getDeptId()));
        params.put("comboId", String.valueOf(mData.getId()));
        params.put("businessDate", FustionManager.mMachineData.getBusinessDate());
        params.put("shift", String.valueOf(FustionManager.mLoginData.getUser().getUser().getShift()));
        params.put("deposit", String.valueOf(mData.getMemberGrade().getDeposit()));
        params.put("admission", String.valueOf(mData.getMemberGrade().getGradeAdmissionFee()));
        params.put("receivableMoney", String.valueOf(mData.getPrice()));
        params.put("actualMoney", String.valueOf(mData.getPrice()));
        params.put("changeMoney", String.valueOf(0));
        params.put("payMethod", String.valueOf(mPayMethod));
        params.put("memberNo", tvCardNum.getText().toString());
        params.put("memberName", etMemName.getText().toString());
        params.put("idNo", etMemPersonNo.getText().toString());
        params.put("phoneNo", etMemPhone.getText().toString());
        params.put("icNo", icNo);
        params.put("gradeId", mData.getGradeId());
        params.put("machineId", FustionManager.mMachineData.getMachineId());
        params.put("machineCode", FustionManager.mMachineData.getMachineCode());
        params.put("authorizeRecords", JSON.toJSON(new ArrayList<>()));

        HttpHelper.RestClientPostRaw(params, HttpUrl.CREATE_CARD_ORDER,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemCardOrderCreatEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        MemCardOrderCreatEntity mData = gson.fromJson(response, type);

                        if (payMethod.equals("1")) {
                            showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                            saleSuitDialog.dismiss();
                        } else if (payMethod.equals("2")) {
                            mCurrentBillNo = mData.getSellBillNo();
                            FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        showShortToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    private void showPayStatusDialog(String status) {

        if (mPayStatusDialog == null) {
            mPayStatusDialog = new MyDialog(getContext(), R.style.dialog);
        }
        mPayStatusDialog.setCancelable(true);
        mPayStatusDialog.show();
        Window window = mPayStatusDialog.getWindow();
        window.setContentView(R.layout.dialog_pay_status);
        int width = (int) (DimenUtil.getScreenWidth() * 0.3);
        int height = (int) (DimenUtil.getScreenHeight() * 0.3);

        window.setLayout(width, height);

        AppCompatImageView ivPayStatusImg = window.findViewById(R.id.iv_status_img);
        AppCompatTextView tvPayStatusTip = window.findViewById(R.id.tv_pay_status_tips);
        AppCompatTextView tvWaitCoinOutTime = window.findViewById(R.id.tv_wait_coin_out_time);

        if (status.equals(FustionTag.PAY_STATUS.WAIT_PAY)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_wait));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAYING)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_paying));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_SUCCESS)) {
            tvPayStatusTip.setText(getString(R.string.suit_pay_success));
            tvWaitCoinOutTime.setVisibility(View.VISIBLE);
            startCountDownTime(5, tvWaitCoinOutTime, mPayStatusDialog);
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_FAILED)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_failed));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        }

        mPayStatusDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                FusionCode.QrIsLoading = false;
                FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            }
        });
    }

    private void startCountDownTime(final long time, final AppCompatTextView tvWaitCoinOut, final Dialog dialog) {
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvWaitCoinOut.setText(String.format(getString(R.string.goods_pay_success), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                dialog.dismiss();

            }
        };
        timer.start();// 开始计时
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (event != null && event.getData() != null) {
            String qrCode = event.getData().getString(FusionString.QR_CODE);
            showShortToast(qrCode);
            qrPay(qrCode, mCurrentBillNo);

        }
    }

    private void qrPay(String qrCode, String billNo) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("authCode", qrCode);
        params.put("billNo", billNo);
        params.put("description", "");
        params.put("totalFee", "0.1");
        params.put("payBillType", "1");

        HttpHelper.RestClientPost(params, HttpUrl.CODE_PAY,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        if (code == 201) {
                            showShortToast("onSuccess:" + code + "||" + response);
                            FusionCode.QrIsLoading = false;
                            showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CardReadEvent event) {
        if (event != null && event.getData() != null) {
            showShortToast("读卡成功");
            isReadNow = false;
            if (StringUtil.isNotEmpty(event.getData().getString("cardNum"))) {
                if (event.getData().getChar("tag") == mCardNoTag) {
                    readCardNum = event.getData().getString("cardNum").replaceFirst("^0*", "").substring(0, 22);
                    if (saleSuitDialog != null) {
                        tvCardNum.setText(CardReadUtil.HexToAscii(readCardNum));
                    }
                } else {
                    createOrder(event.getData().getString("cardNum").substring(0, 18), mPayMethod);
                }
            } else {
                showShortToast("这个卡是空的");
            }

        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

}
